<?php

namespace app\index\controller;

use app\BaseController;
use app\model\Settings;
use app\model\User as ModelUser;
use app\model\UserInfo;
use app\model\UserToken;
use think\facade\Request;
use think\facade\View;

class User extends BaseController
{
    public function generate_token(): string
    {
        $ip = Request::ip();
        if (empty($ip)) {
            $ip = 'tushan';
        }
        for ($i = 0; $i < 10; $i++) {
            $time = strval(time());
            $rang = rand(1000000, 9999999);
            $token = md5($ip . $time . $rang);
            $search = UserToken::where("token", $token)->find();
            if (!$search) {
                return $token;
            }
        }
        //返回一段128字符的md5
        return md5("132465798qwetuyiweqioxcjisdhjkqwbnsajhuixsancijeyduiwqenbxasu" . time());
    }

    //创建用户的系统信息相关资料
    function create_info($uid): bool
    {
        $info = UserInfo::find($uid);
        $total_store = Settings::find("default_storage_size");
        if (empty($info)) {
            $info = new Userinfo;
            $info->uid = $uid;
            $info->files_num = 0;
            $info->use_store = 0;
            $info->total_store = (float)$total_store->value;
            return $info->save();
        }
        return true;
    }

    //退出登录
    public function loginOut(): \think\response\Redirect
    {
        $user = $this->getUser();
        response()->cookie('UserToken', '', 0);
        response()->cookie('UserId', '', 0);
        try {
            UserToken::where('uid', $user['uid'])->where('token', $user['token'])->delete();
        } catch (\Exception $e) {

        }
        return redirect('/');
    }

    /**
     * 用户登录
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $user = $this->request->post('user', false);
            $password = $this->request->post('password', false);
            $code = $this->request->post("code", false);
            $type = $this->request->post("type", 'pass');
            if ($type == 'pass') {
                if (!$user || !$password) {
                    return $this->error("请输入账号和密码");
                }
            }
            if ($type == 'authCode') {
                if (Settings::Config("register") == '0') {
                    return $this->error('管理员已关闭用户注册！');
                }
                if (!$user || !$code) {
                    return $this->error("请输入账号和验证码");
                }
            }
            $md5_password = md5($password);
            if ($type == 'authCode') {
                if ($code && !Sms::codeCheck($user, $code)) {
                    return $this->error("验证码错误");
                }
            }
            $result = ModelUser::where("mobile", $user)->field('status,uid,password,mobile')->find();
            if ($type == 'pass') {
                if ($result) {
                    if ($md5_password != $result['password']) {
                        return $this->error('密码错误！');
                    }
                } else {
                    return $this->error('账户不存在！');
                }
            }
            if (!$result) {
                //注册环节
                $data = [
                    "mobile" => $user
                ];
                ModelUser::create($data);
            }
            $result = ModelUser::where('mobile', $user)->field('status,uid,password,mobile')->find();
            if ($result) {
                if ($result['status'] == 2) {
                    return $this->error("账号已被冻结");
                }
                $token = $this->generate_token();
                unset($result['password']);
                (new \app\model\User)->where("uid", $result['uid'])->update(["update_time" => date("Y-m-d H:i:s")]);
                (new \app\model\UserToken)->insert(["uid" => $result["uid"], "token" => $token, "time" => time(), "ip" => Request::ip()]);
                $result["token"] = $token;
                $this->create_info($result['uid']);
                $dt = [
                    "UserId" => $result['uid'],
                    "UserToken" => $token
                ];
                Sms::codeDestroy($user, $code);
                return $this->success("登录成功", $dt);
            }
            return $this->error("账户不存在！");
        }
        return $this->fetch("user/login");
    }

    //修改密码
    public function safe()
    {
        $info = $this->getUser(true);
        if ($this->request->isAjax()) {
            $passwd = $this->request->post('password', false);
            if ($passwd) {
                if (strlen($passwd) < 6) {
                    return $this->error("密码长度过短");
                }
                $user = ModelUser::where("uid", $info['uid'])->find();
                $user->password = md5($passwd);
                $user->save();

                return $this->success("修改成功");
            }
        }
        return $this->fetch('user/safe', ['title' => '安全中心']);
    }
}
